<template>
  <div>
    <p style="color: #666; font-size: 13px; text-align: center">
      数据并非实时,页面数据来自1小时前，仅供参考，实际以月末统计账单为准
    </p>

    <el-card class="api-log-card">
      <!-- 搜索 -->
      <el-form :inline="true" :model="productData" class="demo-form-inline">
        <el-form-item label="统计方式">
          <el-select
            size="medium"
            v-model="productData.month"
            placeholder="请选择"
            @change="changeSelect()"
          >
            <el-option label="按天查询" value="day"> </el-option>
            <el-option label="按月查询" value="month"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品类型">
          <el-select
            size="medium"
            v-model="productData.type"
            placeholder="请选择"
            clearable
          >
            <el-option label="电信" value="SANYS0"> </el-option>
            <el-option label="联通" value="SANYS1"> </el-option>
            <el-option label="移动" value="SANYS2"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" v-if="timeShow">
          <el-date-picker
            size="medium"
            v-model="productData.startTime"
            type="date"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" v-if="timeShow">
          <el-date-picker
            size="medium"
            v-model="productData.endTime"
            type="date"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期"
          >
          </el-date-picker>
          <!--  :picker-options="pickerOptions" -->
        </el-form-item>
        <el-form-item label="选择月份" v-if="!timeShow">
          <el-date-picker
            size="medium"
            v-model="monthTime"
            type="month"
            placeholder="选择月"
            format="yyyy 年 MM 月"
            value-format="yyyy-MM-dd HH:mm:ss"
            @change="changeMonth"
          >
          </el-date-picker>
        </el-form-item>
        <br />
        <el-form-item label="用户名称" v-if="web_username == 'admin'">
          <el-select
            size="medium"
            v-model="productData.username"
            placeholder="请选择用户名称查询"
            clearable
          >
            <el-option
              :label="item.value"
              :value="item.key"
              v-for="(item, index) in userNameSelect"
              :key="index"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品编号">
          <el-input
            size="medium"
            v-model="productData.productId"
            placeholder="请输入产品编号查询"
            clearable
          ></el-input>
        </el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="medium"
          @click="getproductdata()"
          >总量查询</el-button
        >
        <!-- <el-button
          type="primary"
          :disabled="this.checkeds"
          size="medium"
          icon="el-icon-search"
          v-if="this.$store.state.user.role == 'admin'"
          @click="moneydata()"
          >计费查询</el-button
        > -->

        <el-button
          type="success"
          size="medium"
          icon="el-icon-download"
          @click="exportExcel()"
          >导出表格</el-button
        >
        <el-button
          @click="getDayData()"
          icon="el-icon-search"
          size="medium"
          v-if="timeShow"
          >查询今天</el-button
        >
        <el-button @click="getYesterDayData()" size="medium" v-if="timeShow"
          >查询昨天</el-button
        >
      </el-form>
      <div class="card" v-if="subnum">
        <div class="card1">
          <span>成功调用量</span>
          <hr color="#F8F8F8" />
          {{ ndata.successCount + ndata.errnoCount }}次
        </div>

        <div v-if="this.$store.state.user.role == 'admin'" class="card1">
          <span>计费成功调用量</span>
          <hr color="#F8F8F8" />
          {{ ndata.successCount }}次
        </div>
        <div class="card1">
          <span>失败调用量</span>
          <hr color="#F8F8F8" />
          {{ ndata.errorCount }}次
        </div>
        <div class="card1">
          <span>交易中</span>
          <hr color="#F8F8F8" />
          {{ ndata.errnoCount }}个
        </div>
        <br />
        <div class="card1">
          <span>总调用量</span>
          <hr color="#F8F8F8" />
          {{ ndata.allCount }} 次
        </div>
        <div class="card1">
          <span
            >总消费[参考]
            <hr color="#F8F8F8" />
            ￥</span
          >
          {{ ndata.money }}
        </div>

        <div class="card1">
          <span>成功率</span>
          <hr color="#F8F8F8" />
          {{ String(ndata.successPro * 100).slice(0, 5) }}%
        </div>
      </div>
      <div class="card" v-if="subnum1">
        <div class="card1">
          <span>总调用量</span>
          <hr color="#F8F8F8" />
          {{ ndata.allCount }} 次
        </div>
        <div class="card1">
          <span>计费成功调用量</span>
          <hr color="#F8F8F8" />
          {{ ndata.successCount }}次
        </div>
        <div class="card1">
          <span>失败调用量</span>
          <hr color="#F8F8F8" />
          {{ ndata.errorCount }}次
        </div>
        <br />
        <div class="card1">
          <span
            >总消费[参考值]
            <hr color="#F8F8F8" />
            ￥</span
          >
          {{ ndata.money }}
        </div>

        <div class="card1">
          <span>成功率</span>
          <hr color="#F8F8F8" />
          {{ String(ndata.successPro * 100).slice(0, 5) }}%
        </div>
      </div>
      <!-- <ul class="api-log-ul" v-if="subnum">
        <li>
          <span>总消费[参考]</span><br /><span
            ><span style="color: #000">￥</span>{{ ndata.money }}</span
          >
        </li>
        <li>
          <span>总调用量</span><br /><span
            >{{ ndata.allCount }} <span style="color: #000">次</span>
          </span>
        </li>
        <li>
          <span>成功调用量</span><br /><span
            >{{ ndata.successCount }}<span style="color: #000">次</span></span
          >
        </li>
        <li>
          <span>失败调用量</span><br /><span
            >{{ ndata.errorCount }}<span style="color: #000">次</span></span
          >
        </li>
        <li>
          <span>成功率</span><br /><span
            >{{ String(ndata.successPro * 100).slice(0, 5) }}%</span
          >
        </li>
      </ul>
      <ul class="api-log-ul" v-if="subnum1">
        <li>
          <span>总消费[参考]</span><br /><span
            ><span style="color: #000">￥</span>{{ ndata.money }}</span
          >
        </li>
        <li>
          <span>总调用量</span><br /><span
            >{{ ndata.allCount }} <span style="color: #000">次</span>
          </span>
        </li>
        <li>
          <span>成功调用量</span><br /><span
            >{{ ndata.successCount + ndata.errnoCount
            }}<span style="color: #000">次</span></span
          >
        </li>
        <li>
          <span>失败调用量</span><br /><span
            >{{ ndata.errorCount }}<span style="color: #000">次</span></span
          >
        </li>
        <li>
          <span>成功率</span><br /><span
            >{{ String(ndata.successPro * 100).slice(0, 5) }}%</span
          >
        </li>
      </ul> -->
      <!-- 表格内容 -->
      <el-table
        ref="multipleTable"
        id="tableId2"
        :data="pageList"
        tooltip-effect="dark"
        style="width: 100%"
        v-loading="loadingTable"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        border
      >
        <el-table-column type="index" align="center" width="50">
        </el-table-column>
        <el-table-column label="时间" width="120" align="center">
          <template slot-scope="scope">
            <span style="margin-left: 10px" v-if="timeShow">{{
              scope.row.createTime.slice(0, 10)
            }}</span>
            <span style="margin-left: 10px" v-if="!timeShow">{{
              scope.row.createTime.slice(0, 7)
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="username"
          label="用户名"
          width="150"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="apiKey"
          label="产品编号"
          width="150"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="productName"
          label="产品名称"
          width="230"
          align="center"
        >
        </el-table-column>
        <el-table-column prop="allCount" label="总调用量" align="center">
        </el-table-column>
        <el-table-column label="消费金额" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.successConsume | currency("￥") }}</span>
          </template>
        </el-table-column>
        <el-table-column label="成功调用量" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.successCount + scope.row.errnoCount }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="successCount"
          v-if="this.$store.state.user.role == 'admin'"
          label="计费调用量"
          align="center"
        >
        </el-table-column>

        <el-table-column prop="errorCount" label="失败调用量" align="center">
        </el-table-column>
        <el-table-column label="成功率" align="center">
          <template slot-scope="scope">
            <span style="margin-left: 10px"
              >{{ String(scope.row.successPro * 100).slice(0, 5) }}%</span
            >
          </template>
        </el-table-column>
        <el-table-column label="失败率" align="center">
          <template slot-scope="scope">
            <span style="margin-left: 10px"
              >{{ String(scope.row.errorPro * 100).slice(0, 5) }}%</span
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <!-- currentPage -->
      <el-pagination
        background
        v-if="this.ndata.page.totalCount > 10"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 50, 100, 200]"
        :page-size="10"
        :current-page="productData.pageNum"
        layout="total, sizes, prev, pager, next, jumper"
        :total="ndata.page.totalCount"
      >
      </el-pagination>
    </el-card>
  </div>
</template>
<script>
import { apiScopeCount, getUsername } from "../../../api/sys";
import debounce from "lodash.debounce";
import FileSaver from "file-saver";
import * as XLSX from "xlsx";
export default {
  props: {
    msg: String,
  },
  data() {
    return {
      checkeds: true,
      subnum: false,
      subnum1: false,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() - 86400000 > Date.now();
        },
      },
      // 日期显示与隐藏
      timeShow: false,
      // 搜索条件
      productData: {
        month: "month",
        startTime: "",
        endTime: "",
        type: "",
        productId: "",
        number: 1,
      },
      //   数据
      ndata: {
        page: {
          totalCount: 0,
        },
      },
      pageList: [],
      // 时间
      timeData: [],

      // 月份
      monthTime: "",
      // 加载中
      loadingTable: false,
      userNameSelect: [],
      // 当前用户
      web_username: "",
    };
  },
  mounted() {
    // 获取用户名
    this.getUsername();
    // 获取数据
    // this.getproductdata();
    // 储存当前用户名
    this.web_username = this.$store.state.user.role;
  },
  created() {
    // console.log(this.$store.state.user.role);
    // console.log(this.msg);
  },
  methods: {
    //   导出数据
    exportExcel: debounce(function () {
      //导出当前表格
      var wb = XLSX.utils.table_to_book(document.querySelector("#tableId2")); //表格id
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          "调用量详情.xlsx"
        ); //文件名
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    }, 500),

    // 获取用户名
    async getUsername() {
      let res = await getUsername();
      this.userNameSelect = res.data;
    },
    //  获取数据
    async priceData() {
      this.loadingTable = true;
      try {
        if (this.productData.endTime) {
          this.productData.endTime =
            this.productData.endTime.slice(0, 10) + " " + "23:59:59";
        }
        let res = await apiScopeCount(this.productData);
        if (res) {
          this.subnum = true;
          this.subnum1 = false;
          this.checkeds = false;
        } else {
        }
        // console.log(res);
        this.ndata = res.data;
        this.pageList = res.data.page.pageList;
        this.loadingTable = false;
      } catch (error) {
        console.log(error);
        this.$message({
          message: "获取数据失败，请稍后再试！！!",
          type: "error",
        });
        this.pageList = [];
        this.loadingTable = false;
      }
    },
    // 查询今天数据
    getDayData() {
      let date = null;
      date = new Date();
      let month = (date.getMonth() + 1).toString().padStart(2, "0");
      let year = date.getFullYear();
      let day = new Date().getDate().toString().padStart(2, "0");
      let startTime = year + "-" + month + "-" + day + " " + "00:00:00";
      let endTime = year + "-" + month + "-" + day + " " + "23:59:59";
      this.productData.startTime = startTime;
      console.log(11, new Date().getDate().toString().padStart(2, "0"));
      console.log(month, startTime, endTime);
      this.productData.endTime = endTime;
      this.getproductdata();
    },
    moneydata() {
      this.subnum1 = true;
      this.subnum = false;
    },
    // 获取日期
    getDay(num, str) {
      var today = new Date();
      var nowTime = today.getTime();
      var ms = 24 * 3600 * 1000 * num;
      today.setTime(parseInt(nowTime + ms));
      var oYear = today.getFullYear();
      var oMoth = (today.getMonth() + 1).toString();
      if (oMoth.length <= 1) oMoth = "0" + oMoth;
      var oDay = today.getDate().toString();
      if (oDay.length <= 1) oDay = "0" + oDay;
      return oYear + str + oMoth + str + oDay;
    },
    // 查询昨天数据
    getYesterDayData() {
      let date = this.getDay(-1, "-");
      let startTime = date + " " + "00:00:00";
      let endTime = date + " " + "23:59:59";
      this.productData.startTime = startTime;
      this.productData.endTime = endTime;
      this.getproductdata();
    },
    // 搜索
    getproductdata: debounce(function () {
      // type 类型  productId  产品编号  username 用户名
      let { type, productId, username } = this.productData;
      let typejudge = true;
      if (type && productId) {
        typejudge = productId.includes(type);
      }

      if (typejudge) {
        if (this.web_username != "admin") {
          this.productData.username = this.web_username;
        }
        if (type && productId & username) {
          this.productData.number = 7;
        } else if (username && productId) {
          this.productData.number = 6;
        } else if (type && productId) {
          this.productData.number = 5;
        } else if (type && username) {
          this.productData.number = 4;
        } else if (type) {
          this.productData.number = 3;
        } else if (productId) {
          this.productData.number = 2;
        } else if (username) {
          this.productData.number = 1;
        } else {
          if (this.web_username == "admin") {
            this.productData.number = 0;
          }
        }
        this.productData.pageNum = 1;
        let startTime = this.productData.startTime;
        let endTime = this.productData.endTime;

        if (this.productData.month == "month") {
          if (!this.monthTime) {
            this.getMonth();
          }
        } else {
          if (!startTime || !endTime) {
            this.getMonth();
          }
        }
        this.priceData();
      } else {
        this.$message({
          message: "你的产品编号跟你的产品类型不符,请重新选择！！!",
          type: "warning",
        });
      }
    }, 1000),
    //   下拉框
    changeSelect() {
      if (this.productData.month == "month") {
        this.monthTime = "";
        this.timeShow = false;
      } else {
        this.productData.startTime = "";
        this.productData.endTime = "";
        this.timeShow = true;
      }
    },
    // 分页查询
    async handleSizeChange(val) {
      this.productData.pageSize = val;
      this.priceData();
    },
    async handleCurrentChange(val) {
      this.productData.pageNum = val;
      this.priceData();
    },
    // 选择月份
    changeMonth(value) {
      this.getMonth(value);
    },
    // 获取月份时间
    getMonth(value) {
      let date = null;
      if (value) {
        date = new Date(value);
      } else {
        date = new Date();
      }
      let month = (date.getMonth() + 1).toString().padStart(2, "0");
      let year = date.getFullYear();
      let startTime = year + "-" + month + "-" + "01" + " " + "00:00:00";
      let day = new Date(year, month, 0);
      let endTime = year + "-" + month + "-" + day.getDate() + " " + "23:59:59";
      // return { startTime, endTime };
      this.productData.startTime = startTime;
      this.productData.endTime = endTime;
    },
  },
};
</script>
<style scoped>
.card {
  width: 100%;
  text-align: center;
}
.card1 {
  display: inline-block;
  white-space: nowrap;
  width: 33%;
  font-size: 1rem;
  font-family: "Franklin Gothic Medium", "Arial Narrow", Arial, sans-serif;
  background-color: #fff;
  color: #409eff;
}
.card1 span {
  color: #666;
  font-family: serif;
  font-weight: 600;
}
</style>
<style scoped lang="scss">
.api-log-card {
  position: relative;
  .api-log-ul {
    margin: 0;
    padding: 0;
    float: right;
    list-style: none;
    display: flex;
    // z-index: 99;
    margin-bottom: 20px;
    li {
      width: 110px;
      text-align: center;
      line-height: 24px;
      border-radius: 5px;
      color: #666;
      box-shadow: 2px 2px #e4e5e6;
      border: #e4e5e6 1px solid;
      border-radius: 4px;
      margin-left: 10px;
      padding: 4px 0;
      span:nth-child(1) {
        color: #000;
        font-weight: 600;
      }
      span:nth-child(3) {
        color: #ff0017;
        font-weight: 600;
        font-size: 14px;
      }
    }
  }
}
</style>
